/**
  * @file	spi.c
  *	@author	yoyoyes
  * @date	2023-6-7
  */

#include "spi.h"

/**
  * @func	gd_hal_spi0_init
  * @param	none
  * @return	none
  */
void gd_hal_spi0_init(void)
{
	spi_parameter_struct spi_parameter;
	
	rcu_periph_clock_enable(RCU_SPI0);
	rcu_periph_clock_enable(RCU_GPIOA);
	
	gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_5 | GPIO_PIN_7);
	gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
	
	spi_i2s_deinit(SPI0);										
	spi_parameter.device_mode = SPI_MASTER;					
	spi_parameter.trans_mode = SPI_TRANSMODE_FULLDUPLEX;					/* 全双工模式 */
	spi_parameter.frame_size = SPI_FRAMESIZE_8BIT;				
	spi_parameter.nss = SPI_NSS_SOFT;
	spi_parameter.endian = SPI_ENDIAN_MSB;
	spi_parameter.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
	spi_parameter.prescale = SPI_PSC_2;
	spi_init(SPI0, &spi_parameter);
	spi_enable(SPI0);
}

/**
  * @func	gd_hal_spi0_init
  * @param	spi_periph	SPIx
  * @param	data		读写数据
  * @return	接收数据
  */
uint8_t spi_read_write_byte(uint32_t spi_periph, uint8_t data)
{
	while(spi_i2s_flag_get(spi_periph, SPI_FLAG_TBE) != 1);					/* 发送缓冲区空 */
	spi_i2s_data_transmit(spi_periph, data);
	while(spi_i2s_flag_get(spi_periph, SPI_FLAG_RBNE) != 1);				/* 接收缓冲区非空 */
	
	return spi_i2s_data_receive(spi_periph);
}

/**
  * @func	spi_write_data
  * @param	spi_periph	SPIx
  * @param	data	数据
  * @param	len		长度
  * @return	none
  */
void spi_write_data(uint32_t spi_periph, uint8_t *data, uint16_t len)
{
	uint16_t i;
	
	for(i = 0; i < len; i++)
	{
		spi_read_write_byte(spi_periph, data[i]);
	}
}

/**
  * @func	spi_write_data
  * @param	spi_periph	SPIx
  * @param	data	数据
  * @param	len		长度
  * @return	none
  */
void spi_read_data(uint32_t spi_periph, uint8_t *data, uint16_t len)
{
	uint16_t i;
	
	for(i = 0; i < len; i++)
	{
		data[i] = spi_read_write_byte(spi_periph, 0xff);
	}
}

/**
  * @func	gd_hal_spi_init
  * @param  none
  * @return	none
  */
void gd_hal_spi_init(void)
{
	gd_hal_spi0_init();
}
